package cn.itcast.task;

import cn.itcast.lock.RedisLockFactory;
import cn.itcast.lock.SimpleRedisLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class HelloJob2 {

    @Autowired
    private RedisLockFactory factory;

    @Scheduled(cron = "0/10 * * * * ?")
    public void job() throws InterruptedException {
        // 获取锁对象
        SimpleRedisLock lock = factory.getSimpleRedisLock("lock");
        try {
            // 尝试获取锁
            log.info("正在尝试获取锁");
            boolean isLock = lock.tryLock(50);
            if(!isLock){
                // 获取锁失败
                log.error("获取锁失败，任务结束！");
                return;
            }
            log.info("获取锁成功，开始执行任务！");
            // 模拟任务的耗时
            Thread.sleep(500);
        } finally {
            // 释放锁
            log.warn("任务执行结束，释放锁！");
            lock.unlock();
        }
    }
}
